import string,time
import gobject
import os
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import rb
import rhythmdb
import urllib
globalshell = None
class RhythmRemotePlugin (rb.Plugin):
	def __init__(self):
		rb.Plugin.__init__(self)
	def activate(self, shell):
		try:
			self.server = HTTPServer(('', 8080), MyHandler)
			print 'started httpserver...'
			self._watch_cb_id = gobject.io_add_watch(self.server.socket, gobject.IO_IN, self._idle_cb)
			self.shell = shell
			global globalshell
			globalshell = shell
#			self.shell_cb_ids = (
#				globalshell.props.shell_player.connect('playing-song-changed',
#				self._playing_entry_changed_cb)
#			)
		except:
			self.server.socket.close()
	def deactivate(self, shell):
		print 'shutting down httpserver...'
		del self.shell
		self.server.socket.shutdown(2)
		self.server.socket.close()
		del self.server
#		self.player.disconnect(self.shell_cb_ids)
	def _idle_cb(self, source, cb_condition):
		self.server.handle_request()
		return True
#	def _playing_entry_changed_cb(self, player, entry):
#		self.server.playing_entry_changed(entry)

class MyHandler(BaseHTTPRequestHandler):
	def playing_entry_changed(self, entry):
			print "found entry"
			try:
				tempcoverpath = self.coverpath
			except Exception:
				tempcoverpath = None
			self.title = globalshell.props.db.entry_get(entry, rhythmdb.PROP_TITLE)
			self.artist = globalshell.props.db.entry_get(entry, rhythmdb.PROP_ARTIST)			
			self.album = globalshell.props.db.entry_get(entry, rhythmdb.PROP_ALBUM)					
			self.filepath = globalshell.props.db.entry_get(entry, rhythmdb.PROP_LOCATION)
			self.duration = globalshell.props.db.entry_get(entry, rhythmdb.PROP_DURATION)
			self.filepath = os.path.dirname(self.filepath)
			self.filepath = self.filepath[7:]
			self.filepath = urllib.unquote(self.filepath)#replace("%20"," ")
			self.coverpath = os.path.expanduser("~") + "/.gnome2/rhythmbox/plugins/rhythmremote/rhythmbox-missing-artwork.png"
			#self.coverpath = "/home/fabian/Downloads/rhythmote/images/gnome-dev-ipod.png"
			for filename in os.listdir(self.filepath):
				if os.path.isfile(os.path.join(self.filepath, filename)):
					if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png") or filename.endswith(".gif") or filename.endswith(".svg"):
						self.coverpath = os.path.join(self.filepath,filename)
						break
			print self.coverpath
			if not tempcoverpath == self.coverpath:
				fileObj = open(self.coverpath,"rb")
				self.cover = fileObj.read()
				fileObj.close()
	def setup(self):
		BaseHTTPRequestHandler.setup(self)
		print "initialisation successfull!"
		self.duration = 1000
		self.entry = globalshell.get_player().get_playing_entry()
		if self.entry:
			self.playing_entry_changed(self.entry)
	def do_GET(self):
		try:
			if self.path.endswith("/"):
				self.send_response(200)
				self.send_header('Content-type', 'text/html')
				self.end_headers()
				fileObj = open(os.path.expanduser("~") + "/.gnome2/rhythmbox/plugins/rhythmremote/head.html","rb")
				self.wfile.write(fileObj.read()) #read the static html head and send it to the client
				fileObj.close
				if self.entry:
					self.wfile.write("<img id='cover' src='cover.jpg' width='250' height='250'/><br/>\n")
					self.wfile.write("<div id='currentSong'>"+self.artist.encode('utf-8') + " - " + self.title + "</div><br/>")					
				else:
					self.wfile.write("<div id='currentSong'> Nothing playing ...</div><br/>")			
				self.wfile.write("<input type='button' onclick=\"sendCommand('prev');\" value='<<'/>\n")
				if not globalshell.props.shell_player.get_playing():
					self.wfile.write("<input type='button' id='playButton' onclick=\"sendCommand('play');\" value='>'/>\n")
				else:
					self.wfile.write("<input type='button' id='playButton' onclick=\"sendCommand('pause');\" value='II'/>\n")
				self.wfile.write("<input type='button' onclick=\"sendCommand('next');\" value='>>'/>\n")
				self.wfile.write("</div>\n</body>\n</html>")
				return
			if self.path.endswith("/play") or self.path.endswith("/pause"):   #play
				globalshell.props.shell_player.playpause()
				self.send_response(200)
				self.send_header('Content-type', 'text/html')
				self.end_headers()
				return
			if self.path.endswith("/prev"):   #previous
				globalshell.props.shell_player.do_previous()
				self.send_response(200)
				self.send_header('Content-type', 'text/html')
				self.end_headers()
				return
			if self.path.endswith("/next"):   #next
				globalshell.props.shell_player.do_next()
				self.send_response(200)
				self.send_header('Content-type', 'text/html')
				self.end_headers()
				return
			if self.path.endswith("/artist"):
				self.send_response(200)
				self.send_header('Content-type', 'text/xml')
				self.end_headers()
				self.wfile.write(self.artist)
				return
			if self.path.endswith("/title"):
				self.send_response(200)
				self.send_header('Content-type', 'text/xml')
				self.end_headers()
				self.wfile.write(self.title)
				return
			if self.path.endswith("/isPlaying"):
				self.send_response(200)
				self.send_header('Content-type', 'text/xml')
				self.end_headers()
				if not globalshell.props.shell_player.get_playing():
					self.wfile.write("false")
				else:
					self.wfile.write("true")
				return
			if self.path.endswith("/currentSong"):
				self.send_response(200)
				self.send_header('Content-type', 'text/xml')
				self.end_headers()
				if self.entry:
					self.wfile.write(self.artist + " - " + self.title)
				else:
					self.wfile.write("Nothing playing..")
				return
			if self.path.startswith("/cover.jpg"):
				if not self.coverpath:
					self.send_error(404,'Nothing playing..')
				else:
					self.send_response(200)
					if self.coverpath.endswith(".jpg") or self.coverpath.endswith(".jpeg"):
						self.send_header('Content-type', 'image/jpeg')
					elif self.coverpath.endswith(".png"):
						self.send_header('Content-type', 'image/png')
					elif self.coverpath.endswith(".gif"):
						self.send_header('Content-type', 'image/gif')
					elif self.coverpath.endswith(".svg"):
						self.send_header('Content-type', 'image/svg+xml')
					self.end_headers()
					self.wfile.write(self.cover)
				return
			else:
				self.send_error(404,'This function has not been implemented yet: %s.' % self.path)
			return
		except Exception as e:
			self.send_error(404,'An unknown exception occured: %s' % e)
#		return